<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言NSString 这个类，在 OC 中很常见，[NSString stringWithFormat:] 这个方法我们都很熟悉了。但是也有很常见的一个问题，那就是参数为空的时候会返回@&amp;quot;(null)&amp;quot;。 举个例子 1label.text = [NSString stringWithFormat:@&quot;所在医院 : %@&quot;, self.doctor.hospital]; 当 do">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="解决NSString stringWithFormat:参数nil时返回(null)">
<meta property="og:url" content="https://bingozb.github.io/2.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="前言NSString 这个类，在 OC 中很常见，[NSString stringWithFormat:] 这个方法我们都很熟悉了。但是也有很常见的一个问题，那就是参数为空的时候会返回@&amp;quot;(null)&amp;quot;。 举个例子 1label.text = [NSString stringWithFormat:@&quot;所在医院 : %@&quot;, self.doctor.hospital]; 当 do">
<meta property="og:updated_time" content="2017-09-04T19:06:07.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="解决NSString stringWithFormat:参数nil时返回(null)">
<meta name="twitter:description" content="前言NSString 这个类，在 OC 中很常见，[NSString stringWithFormat:] 这个方法我们都很熟悉了。但是也有很常见的一个问题，那就是参数为空的时候会返回@&amp;quot;(null)&amp;quot;。 举个例子 1label.text = [NSString stringWithFormat:@&quot;所在医院 : %@&quot;, self.doctor.hospital]; 当 do">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/2.html"/>





  <title>解决NSString stringWithFormat:参数nil时返回(null) | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/2.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                解决NSString stringWithFormat:参数nil时返回(null)
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-01-05T00:15:19+08:00">
                2017-01-05
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/解决方案/" itemprop="url" rel="index">
                    <span itemprop="name">解决方案</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2.html" class="leancloud_visitors" data-flag-title="解决NSString stringWithFormat:参数nil时返回(null)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>NSString 这个类，在 OC 中很常见，<code>[NSString stringWithFormat:]</code> 这个方法我们都很熟悉了。但是也有很常见的一个问题，那就是参数为空的时候会返回<code>@&quot;(null)&quot;</code>。</p>
<p><strong>举个例子</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">label.text = [<span class="built_in">NSString</span> stringWithFormat:<span class="string">@"所在医院 : %@"</span>, <span class="keyword">self</span>.doctor.hospital];</div></pre></td></tr></table></figure>
<p>当 doctor.hospital 为 nil 时，显示“所在医院 : (null)”，理所当然 (null) 这样的字眼不应该出现在界面上被用户看见。</p>
<a id="more"></a>
<h2 id="解决"><a href="#解决" class="headerlink" title="解决"></a>解决</h2><h3 id="方法一、使用宏"><a href="#方法一、使用宏" class="headerlink" title="方法一、使用宏"></a>方法一、使用宏</h3><h4 id="定义一个宏，写到PCH文件中"><a href="#定义一个宏，写到PCH文件中" class="headerlink" title="定义一个宏，写到PCH文件中"></a>定义一个宏，写到PCH文件中</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#define DKNonnullString(str) ((str &amp;&amp; [str isKindOfClass:[NSString class]] &amp;&amp; str.length) ? str : @<span class="meta-string">""</span>)</span></div></pre></td></tr></table></figure>
<h4 id="可变参数每一个都包上这个宏"><a href="#可变参数每一个都包上这个宏" class="headerlink" title="可变参数每一个都包上这个宏"></a>可变参数每一个都包上这个宏</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">label.text = [<span class="built_in">NSString</span> stringWithFormat:<span class="string">@"所在医院 : %@"</span>, DKNonnullString(<span class="keyword">self</span>.doctor.hospital)];</div></pre></td></tr></table></figure>
<h4 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h4><p>先判断参数是否为 nil，如果是，就把它替换为空字符串，再进行 format。</p>
<h4 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h4><p>虽然可以实现，但这样子每次调用的时候每个参数都要包一个宏，感觉很麻烦！网上逛了一圈包括 stackoverflow 有人提到都是这样子解决的。程序猿是无法忍受这种重复累赘的，至少我是这样子的，那有没有更酷的办法呢？</p><p></p>
<h3 id="方法二、使用分类"><a href="#方法二、使用分类" class="headerlink" title="方法二、使用分类"></a>方法二、使用分类</h3><p>跳到头文件 NSString.h 中，可以看到与之相关的方法。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">+ (<span class="keyword">instancetype</span>)stringWithFormat:(<span class="built_in">NSString</span> *)format, ... <span class="built_in">NS_FORMAT_FUNCTION</span>(<span class="number">1</span>,<span class="number">2</span>);</div><div class="line">- (<span class="keyword">instancetype</span>)initWithFormat:(<span class="built_in">NSString</span> *)format, ... <span class="built_in">NS_FORMAT_FUNCTION</span>(<span class="number">1</span>,<span class="number">2</span>);</div><div class="line">- (<span class="keyword">instancetype</span>)initWithFormat:(<span class="built_in">NSString</span> *)format arguments:(va_list)argList <span class="built_in">NS_FORMAT_FUNCTION</span>(<span class="number">1</span>,<span class="number">0</span>);</div></pre></td></tr></table></figure>
<p><strong>首先需要了解 initWithFormat: 和 stringWithFormat: 的区别</strong></p>
<table>
<thead>
<tr>
<th>initWithFormat:</th>
<th>stringWithFormat:</th>
</tr>
</thead>
<tbody>
<tr>
<td>实例方法</td>
<td>类方法</td>
</tr>
<tr>
<td>非autoRelease，MRC下需要手动release</td>
<td>autoRelease，推荐使用</td>
</tr>
</tbody>
</table>
<p>在MRC下这两种方式生成的字符串在内存管理上面有点差异，现在的项目绝大部分都是ARC了，所以两者可以说是没有区别的，也就是两者之间可以互换！这是重点！</p>
<p><strong>再来看看 arguments</strong></p>
<p>可以看到参数类型是 va_list，这货一看就不像是 OC 的东西，应该是 C 语言或  C++的。网上一搜，果然跟猜想的一样。它的意思是参数列表，除了 va_list，还有 va_start、va_arg、va_end、NS_FORMAT_FUNCTION，都是 C 语言提供的处理变长参数的方法。</p>
<p><strong>结合这两点，给 NSString 添加一个分类，添加 dk_stringWithFormat: 方法。</strong></p>
<h4 id="NSString-DKExtension-h"><a href="#NSString-DKExtension-h" class="headerlink" title="NSString+DKExtension.h"></a>NSString+DKExtension.h</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 格式化字符串，并过滤格式化后的字符串中的(null)</div><div class="line"></div><div class="line"> @param format 格式</div><div class="line"> @return 格式化后，过滤掉@"(null)"的字符串</div><div class="line"> */</div><div class="line"> + (<span class="keyword">instancetype</span>)dk_stringWithFormat:(<span class="built_in">NSString</span> *)format, ... <span class="built_in">NS_FORMAT_FUNCTION</span>(<span class="number">1</span>,<span class="number">2</span>);</div></pre></td></tr></table></figure>
<h4 id="NSString-DKExtension-m"><a href="#NSString-DKExtension-m" class="headerlink" title="NSString+DKExtension.m"></a>NSString+DKExtension.m</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">+ (<span class="keyword">instancetype</span>)dk_stringWithFormat:(<span class="built_in">NSString</span> *)format, ... <span class="built_in">NS_FORMAT_FUNCTION</span>(<span class="number">1</span>,<span class="number">2</span>)</div><div class="line">&#123;</div><div class="line">    va_list arglist;</div><div class="line">    va_start(arglist, format);</div><div class="line">    <span class="built_in">NSString</span> *outStr = [[<span class="built_in">NSString</span> alloc] initWithFormat:format arguments:arglist];</div><div class="line">    va_end(arglist);</div><div class="line">        </div><div class="line">    <span class="keyword">if</span> ([outStr containsString:<span class="string">@"(null)"</span>])</div><div class="line">        <span class="keyword">return</span> [outStr stringByReplacingOccurrencesOfString:<span class="string">@"(null)"</span> withString:<span class="string">@""</span>];</div><div class="line">    <span class="keyword">return</span> outStr;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>参数说明</strong></p>
<table>
<thead>
<tr>
<th>方法</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>NS_FORMAT_FUNCTION(1, 2)</td>
<td>告诉编译器，索引1处的参数是一个格式化字符串，而实际参数从索引2处开始</td>
</tr>
<tr>
<td>va_list</td>
<td>定义一个指向个数可变的参数列表的指针，这个参数列表指针就是 arglist</td>
</tr>
<tr>
<td>va_start</td>
<td>使参数列表指针指向 format，从 format 的下一个元素开始</td>
</tr>
<tr>
<td>va_end</td>
<td>结束，清空 va_list 可变参数列表</td>
</tr>
</tbody>
</table>
<p><strong>调用</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSString</span> *nilStr = [<span class="built_in">NSString</span> stringWithFormat:<span class="string">@"过滤前的[nil] -&gt; [%@] "</span>,<span class="literal">nil</span>];</div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"%@"</span>,nilStr);</div><div class="line"></div><div class="line"><span class="built_in">NSString</span> *nonullStr = [<span class="built_in">NSString</span> dk_stringWithFormat:<span class="string">@"过滤后的[nil] -&gt; [%@] "</span>,<span class="literal">nil</span>];</div><div class="line"><span class="built_in">NSLog</span>(<span class="string">@"%@"</span>,nonullStr);</div></pre></td></tr></table></figure>
<p><strong>打印</strong></p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">2017<span class="selector-tag">-01-05</span> 00<span class="selector-pseudo">:25</span><span class="selector-pseudo">:19.486</span> <span class="selector-tag">DKExtensionExample</span><span class="selector-attr">[82935:4502309]</span> 过滤前的<span class="selector-attr">[nil]</span> <span class="selector-tag">-</span>&gt; <span class="selector-attr">[(null)]</span> </div><div class="line">2017<span class="selector-tag">-01-05</span> 00<span class="selector-pseudo">:25</span><span class="selector-pseudo">:19.487</span> <span class="selector-tag">DKExtensionExample</span><span class="selector-attr">[82935:4502309]</span> 过滤后的<span class="selector-attr">[nil]</span> <span class="selector-tag">-</span>&gt; <span class="selector-attr">[]</span></div></pre></td></tr></table></figure>
<h4 id="原理-1"><a href="#原理-1" class="headerlink" title="原理"></a>原理</h4><p>添加一个方法，使用 C 语言提供的处理变长参数的方法获取参数列表，调用 initWithFormat:arguments: 方法，把格式化后的字符串在 return 前做过滤处理，把<code>@&quot;(null)&quot;</code>全部替换成<code>@&quot;&quot;</code>。</p>
<h3 id="头脑风暴"><a href="#头脑风暴" class="headerlink" title="头脑风暴"></a>头脑风暴</h3><p>原本我有个想法，是在 NSString 的分类中直接重写 stringWithFormat:，即下面的方法三，原因有两个。</p>
<ol>
<li>在分类中重写系统的方法，无需引入分类文件，load 完毕就生效。</li>
<li>调用方式不需要改，依然是 <code>[NSString stringWithFormat:]</code>，不用改变习惯。</li>
</ol>
<h3 id="方法三、在-NSString-的分类中直接重写-stringWithFormat-（不推荐）"><a href="#方法三、在-NSString-的分类中直接重写-stringWithFormat-（不推荐）" class="headerlink" title="方法三、在 NSString 的分类中直接重写 stringWithFormat:（不推荐）"></a>方法三、在 NSString 的分类中直接重写 stringWithFormat:<em>（不推荐）</em></h3><p>NSString+DKExtension.m</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 重写系统方法，替换返回的字符串中的 (null) 为空字符串</div><div class="line"> *  @"(null)" -&gt; @""</div><div class="line"> */</div><div class="line">+ (<span class="keyword">instancetype</span>)stringWithFormat:(<span class="built_in">NSString</span> *)format, ...</div><div class="line">&#123;</div><div class="line">    va_list arglist; </div><div class="line">    va_start(arglist, format); </div><div class="line">    <span class="built_in">NSString</span> *outStr = [[<span class="built_in">NSString</span> alloc] initWithFormat:format arguments:arglist];</div><div class="line">    va_end(arglist); </div><div class="line"> </div><div class="line">    <span class="keyword">if</span> ([outStr containsString:<span class="string">@"(null)"</span>]) </div><div class="line">        <span class="keyword">return</span> [outStr stringByReplacingOccurrencesOfString:<span class="string">@"(null)"</span> withString:<span class="string">@""</span>];</div><div class="line">    <span class="keyword">return</span> outStr;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在 Demo 中测试没有问题，但引入到实际项目后发现，在某个很正常的界面就崩溃了。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-05</span> <span class="number">21</span>:<span class="number">17</span>:<span class="number">02.087</span> YouYun[<span class="number">85270</span>:<span class="number">4528882</span>] exceptionString:name:</div><div class="line"><span class="built_in">NSInvalidArgumentException</span></div><div class="line">reason:</div><div class="line">Attempt to mutate immutable object with replaceOccurrencesOfString:withString:options:range:</div><div class="line">callStackSymbols:</div><div class="line"><span class="number">0</span>   CoreFoundation                      <span class="number">0x000000010f58634b</span> __exceptionPreprocess + <span class="number">171</span></div><div class="line"><span class="number">1</span>   libobjc.A.dylib                     <span class="number">0x000000010e8b721e</span> objc_exception_throw + <span class="number">48</span></div><div class="line"><span class="number">2</span>   CoreFoundation                      <span class="number">0x000000010f5ef265</span> +[<span class="built_in">NSException</span> raise:format:] + <span class="number">197</span></div><div class="line"><span class="number">3</span>   CoreFoundation                      <span class="number">0x000000010f4ec91b</span> -[__NSCFString replaceOccurrencesOfString:withString:options:range:] + <span class="number">123</span></div><div class="line">...</div></pre></td></tr></table></figure>
<p>除了我们手动调用这个方法，系统自己也会调用这个方法，而且频率是极高的。分析一下异常信息，无效参数异常，原因应该是系统调用某个方法的时候需要一个参数是可变的字符串 NSMutableString, 而我们重写的方法中的 <code>replaceOccurrencesOfString:withString:options:range:</code> 返回了一个不可变的 NSString。</p>
<p>知道原因后，稍做修改。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">+ (<span class="keyword">instancetype</span>)stringWithFormat:(<span class="built_in">NSString</span> *)format, ... <span class="built_in">NS_FORMAT_FUNCTION</span>(<span class="number">1</span>,<span class="number">2</span>)</div><div class="line">&#123;</div><div class="line">    va_list arglist;</div><div class="line">    va_start(arglist, format);</div><div class="line">    <span class="built_in">NSMutableString</span> *outStr = [[<span class="built_in">NSMutableString</span> alloc] initWithFormat:format arguments:arglist];</div><div class="line">    va_end(arglist);</div><div class="line">    </div><div class="line">    <span class="keyword">if</span> ([outStr containsString:<span class="string">@"(null)"</span>]) </div><div class="line">        <span class="keyword">return</span> [<span class="built_in">NSMutableString</span> stringWithString:[outStr stringByReplacingOccurrencesOfString:<span class="string">@"(null)"</span> withString:<span class="string">@""</span>]];</div><div class="line">    <span class="keyword">return</span> outStr;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后跟往常一样调用 <code>[NSString stringWithFormat:]</code> 即可。</p>
<p>也许有人会说，重写了系统的方法，会不会带来其它地方的未知问题。我个人觉得还好吧，虽然重写了 <code>stringWithFormat:</code> 这个方法把返回的字符串中的 @”(null)” 过滤掉了，但实际上还是调用系统的另一个方法 <code>initWithFormat:arguments:</code>。</p>
<p>思前想后，最终我还是放弃了这个解决方案，为什么？</p>
<p>正如上面所说的，系统自己也会调用这个方法，比如下面几个常见的系统调用 format 后的字符串。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">[] -firstOrDefault: (null) success:error:</div><div class="line"></div><div class="line">ClearButton_state:<span class="number">0</span>_variant:<span class="number">0</span>(null)</div><div class="line"></div><div class="line"><span class="number">37.000000</span><span class="number">-12</span><span class="number">-1</span>-<span class="built_in">UIExtendedGrayColorSpace</span> <span class="number">1</span> <span class="number">1</span>-(null)-&#123;<span class="number">0</span>, <span class="number">0</span>&#125;-CW-OutlineShadowOFF</div></pre></td></tr></table></figure>
<p>系统这是在干嘛就不管它了，但说不定苹果还对某些返回的含有@”(null)”的字符串进行了一系列处理呢？比如拿到@”(null)”的 Range，或者判断某个参数 format 后是不是为@”(null)”，然后可能做相对应的处理（纯粹猜想）。如果被我们过滤掉了，也许真的会打乱系统的逻辑导致出现一些莫名其妙的 bug。（暂时没遇到过，如果真想这么玩，需要广大 Coder 在不同项目不同环境下进行检验，目前没有这个人力资本）</p>
<p>所以，我还是决定不去重写系统的方法，就给分类加多一个方法，在我们需要的时候去调用。相对于第一种用宏对每一个参数进行判断过滤的方法来说，我是完全可以接受的。</p>
<h2 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h2><p>如果是在 MRC 下，再调用 autorelease 方法即可。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSString</span> *outStr = [[[<span class="built_in">NSString</span> alloc] initWithFormat:formatStr arguments:arglist] autorelease];</div></pre></td></tr></table></figure>
<h2 id="后话"><a href="#后话" class="headerlink" title="后话"></a>后话</h2><p>我们整理了开发中常用的分类 <a href="https://github.com/bingozb/DKExtension" target="_blank" rel="external">DKExtension</a>，里面已经包含了上面所说的内容，欢迎导入我们的分类库进行开发。</p>
<ul>
<li><p>支持 Cocoapods</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="attribute">pod</span> <span class="string">'DKExtension.h'</span></div></pre></td></tr></table></figure>
</li>
<li><p>Download or Usage 请移步 GitHub, 如果有什么更好的解决方案或者建议，欢迎 GitHub Issues。</p>
</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/2.html" title="解决NSString stringWithFormat:参数nil时返回(null)">https://bingozb.github.io/2.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/4.html" rel="next" title="2016年度工作总结">
                <i class="fa fa-chevron-left"></i> 2016年度工作总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/1.html" rel="prev" title="MySQL支持emoji字符的插入">
                MySQL支持emoji字符的插入 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#解决"><span class="nav-number">2.</span> <span class="nav-text">解决</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方法一、使用宏"><span class="nav-number">2.1.</span> <span class="nav-text">方法一、使用宏</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义一个宏，写到PCH文件中"><span class="nav-number">2.1.1.</span> <span class="nav-text">定义一个宏，写到PCH文件中</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#可变参数每一个都包上这个宏"><span class="nav-number">2.1.2.</span> <span class="nav-text">可变参数每一个都包上这个宏</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原理"><span class="nav-number">2.1.3.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缺点"><span class="nav-number">2.1.4.</span> <span class="nav-text">缺点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法二、使用分类"><span class="nav-number">2.2.</span> <span class="nav-text">方法二、使用分类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#NSString-DKExtension-h"><span class="nav-number">2.2.1.</span> <span class="nav-text">NSString+DKExtension.h</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#NSString-DKExtension-m"><span class="nav-number">2.2.2.</span> <span class="nav-text">NSString+DKExtension.m</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原理-1"><span class="nav-number">2.2.3.</span> <span class="nav-text">原理</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#头脑风暴"><span class="nav-number">2.3.</span> <span class="nav-text">头脑风暴</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法三、在-NSString-的分类中直接重写-stringWithFormat-（不推荐）"><span class="nav-number">2.4.</span> <span class="nav-text">方法三、在 NSString 的分类中直接重写 stringWithFormat:（不推荐）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#补充"><span class="nav-number">3.</span> <span class="nav-text">补充</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后话"><span class="nav-number">4.</span> <span class="nav-text">后话</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
